package com.ynet.middleground.oss.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.base.Throwables;
import com.ynet.core.common.ServiceResult;
import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.middleground.oss.model.OssModel;
import com.ynet.middleground.riskmanage.bean.GetFileReq;
import com.ynet.middleground.riskmanage.bean.UploadReq;
import com.ynet.middleground.riskmanage.dto.FileInfoDTO;

/**
 * @author liulx
 * @description TODO
 * @date 2020-10-16 10:56
 */
@RestController
@RequestMapping("/oss")
public class OssFileController {

    @Autowired
    private OssModel ossModel;

    /**
     * 上传文件至 OSS
     * 
     * @param req
     * @return
     */
    @PostMapping("upload")
    public ServiceResult<String> upload(@RequestBody @Valid UploadReq req) {
        ServiceResult<String> result = new ServiceResult<>();
        try {
            result.setResult(ossModel.upload(req));
        } catch (BusinessException be) {
            result.setError(be.getCode(), be.getMessage());
        } catch (Exception e) {
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "上传文件至 OSS 服务异常, case: {}",
                Throwables.getStackTraceAsString(e));
            result.setError("ECOS0000", "服务异常，请联系系统管理员");
        }
        return result;
    }

    /**
     * 获取文件信息
     * 
     * @param req
     * @return
     */
    @PostMapping("get")
    public ServiceResult<FileInfoDTO> upload(@RequestBody @Valid GetFileReq req) {
        ServiceResult<FileInfoDTO> result = new ServiceResult<>();
        try {
            result.setResult(ossModel.getFileByUrl(req));
        } catch (BusinessException be) {
            result.setError(be.getCode(), be.getMessage());
        } catch (Exception e) {
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "获取文件信息服务异常, case: {}",
                Throwables.getStackTraceAsString(e));
            result.setError("ECOS0000", "服务异常，请联系系统管理员");
        }
        return result;
    }

}
